package com.test.consumer.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
//类上定义熔断fallback方法
@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;


    /**
     * RestTemplate方式发送请求
     */
    @GetMapping("/findAll01")
    public String findAll1(){
        String result = restTemplate.getForObject("http://localhost:10001/user/findAll", String.class);
        return result;
    }


    /**
     * 通过eureka访问其他服务
     */
    @GetMapping("/findAll02")
    public String findAll2(){
        //1.获取service-user实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances("service-user");
        //2.获取实例
        ServiceInstance userInstance = instances.get(0);
        //3.调用服务
        String url = String.format("http://%s:%s/user/findAll", userInstance.getHost(), userInstance.getPort());
        return restTemplate.getForObject(url, String.class);

    }


    /**
     * 使用Ribbon负载均衡
     */
    @GetMapping("/findAll03")
    public String findAll3(){
        String url = "http://service-user/user/findAll";
        return restTemplate.getForObject(url, String.class);

    }


    /**
     * 熔断: 方法上定义fallback
     */
    @HystrixCommand(fallbackMethod = "findAllFallback")
    @GetMapping("/findAll04")
    public String findAll4(){
        String url = "http://service-user/user/findAll";
        return restTemplate.getForObject(url, String.class);

    }

    /**
     * 熔断: 类定义fallback
     */
    @GetMapping("/findAll05")
    @HystrixCommand
    public String findAll5(){
        String url = "http://service-user/user/findAll";
        return restTemplate.getForObject(url, String.class);

    }

    public String findAllFallback(){
        return "方法: 网络有点拥挤(⊙﹏⊙)";
    }


    public String defaultFallback(){
        return "类上: 网络有点拥挤(⊙﹏⊙)";
    }


}
